import { Decorator } from "../core/Decorator";
import { Tick } from "../core/Tick";
import { ActionStatus } from "../core/BaseNode";

export class Repeater extends Decorator {

    maxLoop: number;

    constructor(params?: any) {
        super(params);
        params = params || {maxLoop: -1};
        this.name = 'Repeater';
        this.title = 'Repeat <maxLoop>x';
        this.properties = params
        this.maxLoop = params.maxLoop || -1;
    }

    open(tick: Tick) {
        tick.blackboard.set('i', 0, tick.tree.id, this.id);
    }

    tick(tick: Tick) : ActionStatus {
        if (!this.child) {
            return ActionStatus.ERROR;
        }
        let i = tick.blackboard.get('i', tick.tree.id, this.id);
        let status = ActionStatus.SUCCESS;
        while(this.maxLoop < 0 || i < this.maxLoop) {
            status = this.child._execute(tick);
            if (status === ActionStatus.SUCCESS || status === ActionStatus.FAILURE) {
                i++;
            } else {
                break;
            }
        }
        tick.blackboard.set('i', i, tick.tree.id, this.id);
        return status;
    }
}